const BodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
const nodemailer = require("nodemailer"); // 发送邮箱
const Alipay = require("ali-pay"); // 支付宝支付
const Mock = require("mockjs"); // 生成随机验证码

// 创建连接邮箱的实例
const transporter = nodemailer.createTransport({
  host: "smtp.163.com",
  port: 25, // 163邮箱端口号
  auth: {
    user: "18247113351@163.com", // 管理员邮箱的号码
    pass: "CUXCRWIMUUPHYAQQ", // 邮箱的验证码
  },
});

// 实例化支付宝支付
const pay = new Alipay({
  appId: "2016092000556998",
  publicKey:
    "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiT0kti5gbmdEDBy9PHOucKHNs8pth3hFSEVd9cQt4MZ26n2brRX6MxFlE0JBQVKD/yWkLmEzhcnTgVMdtkYZBWvBBI1lq7tXMDxDD3xKAUrQ+p+RUio4WMUq1G0keFvw2zeib216iU8gb10yZ8oxcZDJLsXq7dc6iV/65AnLaDq1jyeExQuuAU71duOVd53kbHDl4xVaNQQtCby/553R32vhFPG36APwwULXDzWXXtMrsvKddVbo8MsfMQ6+iBmtyHSxOB9vwU5eQQEGkwafCijTc0i8REMOZ8X+Xe0kk9ZfIgvlBm2jTBj5mB4c48sxEYGPRbgl3PMw3OcoOdE+2wIDAQAB",
  privateKey:
    "MIIEowIBAAKCAQEAiT0kti5gbmdEDBy9PHOucKHNs8pth3hFSEVd9cQt4MZ26n2brRX6MxFlE0JBQVKD/yWkLmEzhcnTgVMdtkYZBWvBBI1lq7tXMDxDD3xKAUrQ+p+RUio4WMUq1G0keFvw2zeib216iU8gb10yZ8oxcZDJLsXq7dc6iV/65AnLaDq1jyeExQuuAU71duOVd53kbHDl4xVaNQQtCby/553R32vhFPG36APwwULXDzWXXtMrsvKddVbo8MsfMQ6+iBmtyHSxOB9vwU5eQQEGkwafCijTc0i8REMOZ8X+Xe0kk9ZfIgvlBm2jTBj5mB4c48sxEYGPRbgl3PMw3OcoOdE+2wIDAQABAoIBABaadXN0C/njFDgSe7B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6pyyURTjuny0Skr/TFJEyfyV6MkU4AQpfIFGW10XSuiIIW6+GDOqpV/4DhOQRp+qRD20dFErj+uSRlly61U6E+Vh7WFfPrawm2k37kEdoQ+CvOZ3EBcPyaAloSO4c15",
  // sandbox: true // 是否为沙箱系统测试  默认false
});

// 发送邮箱的方法
const sendEmail = (email) => {
  transporter.sendMail(email, (err, data) => {
    if (err) console.log(err);
    else console.log(data);
  });
};

const userList = [
  {
    username: "admin",
    password: "123",
    name: "张三",
    phone: "1888888888",
    email: "18247113351@163.com",
    id: "1",
  },
  {
    username: "user",
    password: "123",
    name: "李四",
    phone: "1999999999",
    email: "1999999999@163.com",
    id: "2",
  },
];

module.exports = {
  devServer: {
    before: (app) => {
      // 编译post传来的参数
      app.use(BodyParser.json());

      // 对应的接口
      app.post("/api/user/login", (req, res) => {
        // 获取前端传来的参数
        const { username, password } = req.body;

        const info = userList.find(
          (item) => item.username === username && item.password === password
        );

        if (info) {
          res.send({
            code: 1,
            msg: "登录成功",
            token: jwt.sign(info.id, "实训二"),
          });
        } else {
          res.status(401).send({
            code: 0,
            msg: "用户名或者密码错误",
          });
        }
      });

      // 邮箱获取验证码
      app.post("/api/user/getEmailRuleCode", async (req, res) => {
        // 获取邮箱
        const { email } = req.body;

        const info = userList.find((item) => item.email === email);
        if (!info) {
          res.status(404).send({
            code: 0,
            msg: "邮箱不存在，请注册后再试",
          });
        }

        // 生成随机验证码
        const code = Mock.mock("@natural(100000,999999)");

        // 将验证码保存 有效期 1 小时
        const jwtCode = jwt.sign(code + "", email);

        // 发送验证码
        await sendEmail({
          from: "18247113351@163.com", // 发件人
          to: email, // 收件人
          subject: "验证码！！！注意查收",
          html: `验证码为:${code}, 自己偷摸看，别给别人看，看了后果自负，我司不承担责任`,
          text: "发送内容",
        });

        res.send({
          code: 0,
          msg: "验证码发送成功",
          jwtCode,
        });
      });

      // 邮箱登录接口
      app.post("/api/user/emailLogin", (req, res) => {
        // 获取前端传来的参数
        const { email, ruleCode, jwtCode } = req.body;

        if (ruleCode == jwt.verify(jwtCode, email)) {
          // 验证没问题 判断邮箱是否存在
          const info = userList.find((item) => item.email === email);
          if (info) {
            res.send({
              code: 1,
              msg: "登陆成功",
              token: jwt.sign(info.id, "实训二"),
            });
          } else {
            res.status(404).send({
              code: 0,
              msg: "邮箱不存在，请注册后再试",
            });
          }
        } else {
          res.status(401).send({
            code: 0,
            msg: "验证码输入有误，请查证后再试",
          });
        }
      });

      // 获取banner接口
      app.get("/api/user/getBannerList", (req, res) => {
        const imgList = Mock.mock({
          "list|5-8": [
            {
              img: "@image(100x100, @color)",
              id: "@id",
            },
          ],
        });

        res.send({
          code: 1,
          data: imgList.list,
        });
      });

      // 支付接口
      app.post("/api/user/pay", (req, res) => {
        // 获取前端传来的数据
        const { shopName, price } = req.body;

        pay.wapPay(
          {
            subject: shopName, // 支付标题
            totalAmount: price, // 订单金额
          },
          (err, result) => {
            if (err) {
              res.status(502).send({
                code: 0,
                msg: "支付失败，请稍后重试",
              });
            }

            res.send({
              code: 1,
              msg: `支付成功， 恭喜你购买价值${price}元的${shopName}`,
              result,
            });
          }
        );
      });
    },
  },
};
